import { Http } from '@/@nasty/Axios';
import { Principal } from '@/@nasty/Principal';
import { BellOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { SelectLang as UmiSelectLang } from '@umijs/max';
import { Badge, Button, Divider, Empty, List, Popover, Space, Tabs, TabsProps } from 'antd';
import { Typography } from 'antd';
import { useEffect, useState } from 'react';
import VirtualList from 'rc-virtual-list';
import { NoticeAction } from '@/@nasty/NoticeAction';
import { FlowModel } from '@/@nasty/components/Flow';
import React from 'react';

const { Title, Text, Link } = Typography;

export type SiderTheme = 'light' | 'dark';

export const SelectLang = () => {
  return <UmiSelectLang />;
};

export const Question = () => {
  return (
    <div
      style={{
        display: 'flex',
        height: 26,
      }}
      onClick={() => {
        window.open('https://pro.ant.design/docs/getting-started');
      }}
    >
      <QuestionCircleOutlined />
    </div>
  );
};

const PAGE_SIZE = 5;

export const Notice = () => {

  const [dot, setDot] = useState(false);

  useEffect(() => {
    Http.post("/System/UserMessage/GetUserMessageCount", { IsRead: false })
      .then((res) => {
        let count = res.Data || 0;
        setDot(count > 0);
      });
  }, []);

  const read = () => {
    if (dot) {
      Http.post("/System/UserMessage/SetAllUserMessageRead", {}, { isSilence: true })
        .then((res) => {
          setDot(false);
        });
    }
  }

  return (
    <Popover

      destroyOnHidden={true}
      content={<NoticeTab />}
      trigger="click"
      placement="bottom"
    >

      <Badge dot={dot} onClick={() => { read(); }}>
        <BellOutlined style={{ fontSize: "16px", fontStyle: "normal", color: "rgba(0, 0, 0, 0.45)" }} />
      </Badge>
    </Popover>
  )
}

const NoticeTabSystemItem: React.FC<any> = (props) => {
  let item = props.item;
  let index = props.index;
  return (
    <Space size={1} direction="vertical">
      <Text style={{ fontSize: 14 }}>{item.Title}</Text>
      <Text ellipsis style={{ width: 280, fontSize: 14 }}>{item.Description}</Text>
      <Text style={{ fontSize: 12, textAlign: 'right' }}>{item.CreateTime}</Text>
    </Space>
  )
}

const NoticeTabFlowItem: React.FC<any> = (props) => {
  let item = props.item;
  let index = props.index;
  let data = JSON.parse(item.Extend);
  const flowRef = React.useRef(null);

  const openFlow = (v: any) => {
    flowRef.current?.open(v);
  }

  const click = () => {
    let cb = NoticeAction.get(data.Action);
    if (cb) cb(data, openFlow);
  }

  return (
    <>
      <Space size={1} direction="vertical" onClick={() => { click(); }}>
        <Text style={{ fontSize: 14 }}>{item.Title}</Text>
        <Text ellipsis style={{ width: 280, fontSize: 14 }}>{item.Description}</Text>
        <Text style={{ fontSize: 12, textAlign: 'right' }}>{item.CreateTime}</Text>
      </Space>
      <FlowModel ref={flowRef} />
    </>
  )
}

const NoticeTabList: React.FC<any> = (props) => {
  const [initLoading, setInitLoading] = useState(true);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const [list, setList] = useState<any[]>([]);
  const [page, setPage] = useState(1);
  const [end, setEnd] = useState(false);

  const fetchData = (currentPage: number) => {
    let url = props.url;
    let params = props.params;
    return Http.post(url,
      {
        Current: currentPage,
        PageSize: PAGE_SIZE,
        ...params
      });
  };

  useEffect(() => {
    fetchData(page).then((res) => {
      const results = Array.isArray(res.Data) ? res.Data : [];
      setInitLoading(false);
      setData(results);
      setList(results);
      setEnd(res.Current >= res.TotalPage);
    });
  }, []);

  const onLoadMore = () => {
    setLoading(true);
    const nextPage = page + 1;
    setPage(nextPage);
    fetchData(nextPage).then((res) => {
      const results = Array.isArray(res.Data) ? res.Data : [];
      const newData = data.concat(results);
      setData(newData);
      setList(newData);
      setLoading(false);
      setEnd(res.Current >= res.TotalPage);
      //window.dispatchEvent(new Event('resize'));
    });
  };

  const loadMore = !end &&
    !initLoading && !loading ? (
    <div
      style={{
        textAlign: 'center',
        marginTop: 12,
        height: 32,
        lineHeight: '32px',
      }}
    >
      <Button onClick={onLoadMore}>加载更多</Button>
    </div>
  ) : null;

  const onScroll = (e: React.UIEvent<HTMLElement, UIEvent>) => {
    // Refer to: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#problems_and_solutions
    if (
      Math.abs(e.currentTarget.scrollHeight - e.currentTarget.scrollTop - 360) <= 1
    ) {
      onLoadMore();
    }
  };

  if (list.length == 0) return <Empty style={{ padding: 20 }}></Empty>;

  return (
    <List>
      <VirtualList
        data={list}
        height={360}
        itemHeight={1}
        itemKey="Id"
        onScroll={onScroll}
      >
        {(item: any, index: number) => (
          <List.Item key={item.Id}>
            {props.getItem({ item, index })}
          </List.Item>
        )}
      </VirtualList>
    </List>
  )
}


{/* <List
itemLayout="horizontal"
loading={initLoading}
loadMore={loadMore}
dataSource={list}
renderItem={(item, index) => (
  <List.Item key={index}>
    {props.getItem({ item, index })}
  </List.Item>
)}
/> */}

const NoticeTab = () => {
  let info = Principal.getUserInfo();
  let userId = info?.Id || info?.UserId;
  const items: TabsProps['items'] = [
    {
      key: 'system',
      label: '通知',
      children: <NoticeTabList
        getItem={(ps: any) => { return <NoticeTabSystemItem {...ps} /> }}
        url={"/System/UserMessage/GetUserMessagePage"}
        params={{
          UserId: userId,
          MessageTypes: [1, 99] //查询系统消息/全体通知
        }} />,
    },
    {
      key: 'todo',
      label: '待办',
      children: <NoticeTabList
        getItem={(ps: any) => { return <NoticeTabFlowItem {...ps} /> }}
        url={"/System/UserMessage/GetUserMessagePage"}
        params={{
          UserId: userId,
          MessageTypes: [2] //查询流程消息
        }} />,
    },
  ];


  const onChange = (key: string) => {
    console.log(key);
  };

  return <Tabs tabBarStyle={{ marginBottom: "0px" }} style={{ width: "300px", paddingLeft: "10px", paddingRight: "10px" }} defaultActiveKey="1" items={items} onChange={onChange} />
}